package gateway;

import java.util.logging.Level;
import java.util.logging.Logger;

import messageHandle.MessageCenter;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

public class MessageServerHandler extends SimpleChannelUpstreamHandler {
	private static final Logger	logger	= Logger.getLogger(MessageServerHandler.class.getName());
	
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
		// if (!(e.getMessage() instanceof String)) {
		// return;// (1)
		// }
		// String msg = (String) e.getMessage();
		// System.err.println("MessageServerHandler---get-- msg:" + msg);
		// e.getChannel().write(msg);// (2)
		
		ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
		
		MessageCenter.GetInstance().addMsg(buffer, e.getChannel());
		
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		logger.log(Level.WARNING, "Unexpected exception from downstream.", e.getCause());
		e.getChannel().close();
	}
	
	/**
	 * 连接断开
	 */
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		super.channelClosed(ctx, e);
		
		// // 玩家退出
		// Player player = players.remove(ctx);
		// if (player.uid > 0) {
		// // 玩家离开聊天室
		// ChatServer.playerOut(player);
		//
		// DUserInfo userInfo = MUser.getInstance().getUserInfo(player.uid);
		// // 设置为离线
		// userInfo.setOnline(false);
		// userInfo.setLastOffline(DateTime.time());
		// }
		
		System.out.println("Player " + ctx.toString() + " out.");
	}
	
}
